<template>
  <div class="app-container">
     
		<h1>测试webSocket</h1>      
		<button @click="getWebsocket">点击请求后台数据</button>    

  </div>
</template>

<script>
import { webstock } from "@/api/system/info";


export default {
  name: "Dept",
  data() {
    return {
  	num:''
    
    };
  },
  created() {
  this.initWebSocket()   
  },
  destroyed: function () { // 离开页面生命周期函数              
		this.websocketclose();        
	},  
  methods: {
   	initWebSocket: function () {                
			// WebSocket与普通的请求所用协议有所不同，ws等同于http，wss等同于https  
			this.num = Math.random().toFixed(4);
			this.websock = new WebSocket('ws://10.8.3.88:8080/websocket/'+this.num);                
			this.websock.onopen = this.websocketonopen;                
			this.websock.onerror = this.websocketonerror;                
			this.websock.onmessage = this.websocketonmessage;                
			this.websock.onclose = this.websocketclose;              
		},              
		websocketonopen: function () {                
			console.log("WebSocket连接成功");              
		},              
		websocketonerror: function (e) {                
			console.log("WebSocket连接发生错误");              
		},              
		websocketonmessage: function (e) {                
			console.log(e.data);                // console.log(e);              
		},              
		websocketclose: function (e) {                
			console.log("connection closed (" + e.code + ")");              
		},              
		getWebsocket:function(){                
			//var url = "http://10.8.3.88:8080/system/student?shipId=test15"                
			// 这里只是一个基于axios的ajax请求，你可以换成你的请求格式                
		//	this.$ajax.get(url)   

//		var xhr = new XMLHttpRequest();  //这里没有考虑IE浏览器，如果需要择if判断加
//		xhr.open('GET', url,true);
//		xhr.send(null);
//		xhr.onreadystatechange = function () {
//		    if (xhr.status === 200 && xhr.readyState === 4) {
//		        console.log(1)
//		    }
//		}       
		webstock(this.num).then((res)=>{
			console.log(res);
		})
	 }    
	 }
};
</script>